//
//  GoodsTool.m
//  收纳
//
//  Created by  on 2022/10/29.
//

#import "GoodsTool.h"

@implementation GoodsTool
+ (void)find:(BOOL)isContainer complete:(nullable void(^) (NSMutableArray <Goods*>*result))block{
    NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"isContainer"),bg_sqlValue(@(isContainer))];
    [self bg_find:where complete:block];
}
+ (void)update:(Goods*)model complete:(nullable void(^) (BOOL success))block{
    [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (block) {
                [NotifyTool post:notifyGoodsUpdate :nil];
                block(isSuccess);
            }
        });
    }];
}
+ (void)delete:(Goods*)model complete:(nullable void(^) (BOOL success))block{
    NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"stamp"),bg_sqlValue(@(model.stamp))];
    [Goods bg_deleteAsync:nil where:where complete:^(BOOL isSuccess) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (block) {
                [NotifyTool post:notifyGoodsUpdate :nil];
                block(isSuccess);
            }
        });
    }];
}
+ (void)find:(BOOL)isContainer name:(NSString *)name complete:(nullable void(^) (NSMutableArray <Goods*>*result))block{
    NSString* where = @"";
    if (name && name.length > 0) {
        where = [NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"isContainer"),bg_sqlValue(@(isContainer)),bg_sqlKey(@"container"),bg_sqlValue(name)];
    }else{
        where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"isContainer"),bg_sqlValue(@(isContainer))];
    }
    [self bg_find:where complete:block];
}
+ (void)search:(NSString *)text complete:(nullable void(^) (NSMutableArray <Goods*>*result))block{
    NSString *iscontainer = [NSString stringWithFormat:@" %@=%@ ",bg_sqlKey(@"isContainer"),bg_sqlValue(@(YES))];
    NSString *name = [NSString stringWithFormat:@" %@ like '%%%@%%' ",bg_sqlKey(@"name"),text];
    NSString *remark = [NSString stringWithFormat:@" %@ like '%%%@%%' ",bg_sqlKey(@"remark"),text];
    NSString *container = [NSString stringWithFormat:@" %@ like '%%%@%%' ",bg_sqlKey(@"container"),text];
    NSString *money = [NSString stringWithFormat:@" %@ like '%%%@%%' ",bg_sqlKey(@"money"),text];
    NSString* where = [NSString stringWithFormat:@"where%@and%@or%@or%@or%@",iscontainer,name,remark,container,money];
    [self bg_find:where complete:block];
}
+ (void)bg_find:(NSString *)where complete:(nullable void(^) (NSMutableArray <Goods*>*result))block{
    [Goods bg_findAsync:nil where:where complete:^(NSArray * _Nullable array) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (block) {
                block([NSMutableArray arrayWithArray:array]);
            }
        });
    }];
}
@end
